import { createRouter, RouteRecordRaw, Router, createWebHistory, createWebHashHistory } from 'vue-router';
import store from "@/store/index";
import routers from "./router.json";
import NProgress from "nprogress";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'viewProt',
    redirect: "/index",
    meta: {
      hidden: false,
      zh: '视口',
      en: "view port"
    },
    component: () => import("@/viewPort/index.vue"),
    children: [
      {
        path: "index",
        name: "index",
        meta: {
          hidden: false,
          keepAlive: true,
          zh: "首页",
          path: "index",
          en: "home page"
        },
        component: () => import('@/views/index/index.vue'),
      }
    ],

  },
  {
    path: '/login',
    name: 'login',
    meta: {
      hidden: false,
      zh: '登录',
      en: "login"
    },
    component: () => import("@/views/login/index.vue")
  },
  {
    path: "/404",
    name: "notFound",
    component: () => import("@/views/404/index.vue")
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: {
      name: "notFound"
    }
  }
]

const router: Router = createRouter({
  history: createWebHashHistory(),
  // history:createWebHistory(),
  routes
})
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (!store.state.hadAddRoutes) {
    const dynamicRoutes: Array<RouteRecordRaw> = doRouters(routers);
    const firstRoute: any = routes[0].children;
    const renderTree: Array<any> = [
      ...firstRoute,
      ...routers
    ]
    // console.log(dynamicRoutes);
    store.commit("setRenderRouterTree", renderTree);
    dynamicRoutes.forEach((item: any) => {
      if (!router.hasRoute(item.name)) {
        router.addRoute("viewProt", item)
      }
    })
    // router.getRoutes()
    store.commit("setRoutes", router.getRoutes());
    store.commit("setAddRoutes", true)
    console.log("dynamicRoutes has finished")
    if (to.path === "/404") {
      const fromPath = location.href.split("#")[1];
      const findRoute = store.state.routes.find((item: any) => item.path === fromPath)
      if (findRoute) {
        return next({ path: fromPath, replace: true })
      }
    }
    NProgress.done()
    return next({ ...to, replace: true })
  } else {
    NProgress.done()
    return next()
  }
})
// 路由对象接口定义
interface RouterFace {
  path: string,
  name: string,
  meta?: object
  component?: string,
  children?: Array<RouterFace>
}
// 处理路由将路由树拍扁
/**
 * 
 * @param tree 传进去的路由菜单树
 * @returns 
 */
function doRouters(tree: Array<RouterFace>): Array<RouteRecordRaw> {
  const res: Array<RouteRecordRaw> = [];
  /**
   * 
   * @param arr 路由菜单树
   * @param level 当前树层级
   * @param f_ind 父级id
   * @param f_path 父路由
   */
  const p = (arr: Array<RouterFace>, level: number = 0, f_ind: string = "", f_path: string = ""): void => {
    arr.forEach((item, index) => {
      const path: string = f_path ? (f_path + "/" + item.path) : item.path;
      item.meta = {
        ...item.meta,
        level,
        ind: f_ind + index,
        path: path
      }
      if (item.component) {
        const name = path.replace(/\//g, '_');
        console.log(item.component);
        const cacheComponent:string = "dynamicViews_"+ item.component.replace(/\//g, '_');
        res.push({
          ...item,
          path: path,
          name: name,
          meta: {
            cacheComponent:cacheComponent,
            ...item.meta
          },
          children: [],
          component: loadView(item.component)
        })
      }
      if (item.children && item.children.length) {
        p(item.children, level, index + "", path)
      }
    })
  }
  p(tree);
  return res;
}
const modules: any = import.meta.glob("../dynamicViews/**/**.vue")
function loadView(str: string): any {
  return modules[`../dynamicViews/${str}.vue`];
}
export default router